/**
 作者:轨迹
 日期:2015-9-25
 功能: Ajax 以及 jsonp
 */
sky.define(["sky/data/comm"] ,function(require){
    var U = require('util');
    var D = require("sky/data/comm");
    var E = require("emitter");

    function fixedURL(url,param){
        var str = typeof param == 'string' ? param : D.QS.stringify(param,'&');
        if(str){
            return url + (url.indexOf("?") > -1 ? '&' : '?') + str;
        }
        return url;
    }

    //  ==========================JSONP===
    var jsonp = U.extend(E, {
        oncensor:function(){
            if(this.responseJSON){
                return true;
            }
            return "no data back,please try it later...";
        },
        abort:function(){
            // 取消回调
            var node = this.node;
            if(node){
                // 可以删除零时的 回调函数
                window[this.key] = null;
                delete window[this.key];
                this.key = null;
                node.onreadystatechange = node.onload = node.onerror = null;
                this.node = null;
            }
        },
        send:function(param, over){
            var i = this;
            if(!over && i.key){
                return i;
            }
            if(over && i.node){
                // 取消回调
                i.abort();
            }
            if(!param){
                param = {};
            }
            else if(typeof param === 'string'){
                param = D.QS.parse(param);
            }
            i.key = param[i.jsonpKeyStr];
            if(!i.key){
                param[i.jsonpKeyStr] = i.key = '_jsonp_' + U.getSole() + '_';
            }

            window[i.key] = function(data){
                i.responseJSON = data;
            };
            setTimeout(function(){
                i.emit('open', param);
                i.node = U.loadJS(fixedURL(i.url, param),function(){
                    i.abort();
                    var back = i.emit("censor");
                    i.error = back === true ? null : back;
                    i.emit("callback");
                    i.emit(i.error ? "fail" : "success");
                });
            },0);

            return i;
        },
        backKey:'callback'
    },function(url,backKey){
        if(backKey){
            this.backKey = backKey;
        }
        this.url = url;
    });

    // jsonp 跨域加载数据
    function _jsonp(url, callback, param, backKey){
        var i = new jsonp(url,backKey);
        if(callback){
            i.oncallback = callback;
        }
        return i.send(param);
    }

    _jsonp.BaseClass = jsonp;
    _jsonp.fn = jsonp.prototype;
    _jsonp.create = function(url,backKey){
        return new jsonp(url,backKey);
    };

    return _jsonp;
});
